import { acceptHMRUpdate, defineStore } from "pinia";
import { computed, shallowRef } from "vue";
import { existsFile, readDir } from "@/framework/util/fs";
import path from "path-browserify-esm";
import type { GenericToolItemVO } from "@/pages/tools/common/vos";
import { array2object } from "@/framework/util/collections";
import { useLocalRef, useLocalShallowRef } from "@/framework/vue/hooks";
import semver from "semver";

const defaultInstallDir = "C:/Dev/Denv/python";

export const usePythonStore = defineStore("python", () => {
  const installPath = useLocalRef("python.install.path", defaultInstallDir);
  const setInstallPath = (path: string) => (installPath.value = path);

  const versionList = shallowRef<GenericToolItemVO[]>([]);
  const versionMap = computed(() => array2object(versionList.value, "version"));

  const nonInstallerVersions = useLocalShallowRef<Dict<boolean>>("python.non-installer.versions", {});
  const setNonInstallerVersion = (version: string, value: boolean) => {
    return (nonInstallerVersions.value = { ...nonInstallerVersions.value, [version]: value });
  };

  async function scanInstalled() {
    try {
      const list: GenericToolItemVO[] = [];
      const items = await readDir(installPath.value);
      for (const it of items) {
        if (it.startsWith("python-")) {
          const dir = path.join(installPath.value, it);
          const binFile = path.join(dir, "python.exe");
          if (await existsFile(binFile)) {
            const [, , ...omit] = it.split("-");
            list.push({ version: omit.join("-"), installPath: dir, bin: binFile });
          }
        }
      }

      list.sort((a, b) => semver.compare(b.version, a.version));
      versionList.value = list;
    } catch (e: any) {
      console.error("scanInstalledMaven error", e);
      versionList.value = [];
    }
  }

  return {
    installPath: installPath,
    setInstallPath: setInstallPath,

    versionList: versionList,
    versionMap: versionMap,
    scanInstalled: scanInstalled,

    nonInstallerVersions,
    setNonInstallerVersion,
  };
});

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(usePythonStore, import.meta.hot));
}
